package lzupdater.net;

import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import lzupdater.log.Logger;

//LZRosterUpdater, a java client to update LZRoster
//Copyright (C) 2008 Fraskor from Krasus (e-mail: fraskor@gmail.com)
//
//This file is part of LZRosterUpdater.
//
//LZRosterUpdater is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 * 
 * @author Fraskor
 */
public class HTTPHeader {

	private HashMap<String, String> data = new HashMap<String, String>();

	HTTPHeader(HttpURLConnection connection) {
		data.clear();
		for (int i = 0;; i++) {
			String key = connection.getHeaderFieldKey(i);
			String field = connection.getHeaderField(i);
			if (key == null && field == null) {
				break;
			}
			data.put(key, field);
		}
	}

	public String getHeaderField(String key) {
		return data.get(key);
	}

	public void display() {
		display(System.out);
	}

	public void display(PrintStream stream) {
		stream.println(this);
	}

	public void dump(Logger log) {
		for (Entry<String, String> entry : data.entrySet()) {
			log.debug(String.format("%s => '%s'", entry.getKey(), entry
					.getValue()));
		}

	}

	@Override
	public String toString() {
		StringBuffer resultat = new StringBuffer();
		for (Iterator<Entry<String, String>> it = data.entrySet().iterator(); it
				.hasNext();) {
			Entry<String, String> entry = it.next();
			resultat.append(entry.getKey()).append(" => '").append(
					entry.getValue()).append("'");
			if (it.hasNext()) {
				resultat.append("\n");
			}
		}
		return resultat.toString();
	}
}
